#include <nice2d/animation.h>
#include <nice2d/piece/actions/fightanimationaction.h>

IMPLEMENT_OBJECT(FightAnimationAction,FiniteTimeAction)

class FightAnimationActionData
{
public:
    FightAnimationActionData(FiniteTimeAction* action):
        thisAction(action)
    {
        thisAction->started.connect(std::bind(&FightAnimationActionData::onStarted,this));
    }

    FiniteTimeAction* thisAction;
    std::shared_ptr<Scene> scene;
    sf::Vector2f position;
    std::shared_ptr<Animation> animation;

    void onStarted()
    {
        if(animation)
        {
            animation->setCenter(position);
            scene->addChild(animation);
            animation->setDurationPerFrame(thisAction->getDuration());
            animation->start();

            animation->finished.connect(std::bind(&FightAnimationActionData::onStoped,this));
        }
    }

    void onStoped()
    {
        if(animation)
        {
            scene->detachChild(animation);
            thisAction->stop();
        }
    }
};

FightAnimationAction::FightAnimationAction(std::shared_ptr<Scene> scene, const sf::Vector2f &position, float duration):
    FiniteTimeAction(duration),
    data(new FightAnimationActionData(this))
{
    data->scene = scene;
    data->position = position;
}

FightAnimationAction::~FightAnimationAction()
{

}

void FightAnimationAction::setAnimation(std::shared_ptr<Animation> animation)
{
    data->animation = animation;
}
